package cn.softgame.jserver.connector.data;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.commons.io.output.ByteArrayOutputStream;

public class DataTypeHelper {
	
	public static String getString(InputStream in){
		StringBuffer sb = new StringBuffer();
		try {
			InputStreamReader isr = new InputStreamReader(in);
			int buffer;
			while((buffer=isr.read())!=-1){
				sb.append((char)buffer);
			}
			isr.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	public static Object getObject(InputStream in){
		try {
			ObjectInputStream ois = new ObjectInputStream(in);
			Object object = ois.readObject();
			ois.close();
			return object;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static OutputStream writeObject(Object object){
		try {
			OutputStream os = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			oos.writeObject(object);
			oos.close();
			return os;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static OutputStream writeString(String strs){
		try {
			OutputStream os = new ByteArrayOutputStream();
			byte[] bytes = strs.getBytes("UTF-8");
			os.write(bytes, 0, bytes.length);
			return os;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
